package com.dhecp.project.storage.service.impl;

import com.alibaba.fastjson.JSON;
import com.dhecp.common.core.domain.AjaxResult;
import com.dhecp.common.utils.MessageUtils;
import com.dhecp.common.utils.RandomValueUtils;
import com.dhecp.common.utils.TypeUtils;
import com.dhecp.core.constant.DataFiltering;
import com.dhecp.core.utils.PageUtils;
import com.dhecp.core.utils.ReflectUtils;
import com.dhecp.project.business.mapper.FbaLogsticsOrderMapper;
import com.dhecp.project.common.domain.ModuleNID;
import com.dhecp.project.common.domain.RecordCheck;
import com.dhecp.project.common.domain.UpdateFlow;
import com.dhecp.project.common.service.impl.BaseModuleServiceImpl;
import com.dhecp.project.finance.domain.AccountCountForCompany;
import com.dhecp.project.finance.domain.AccountDetailedForCompany;
import com.dhecp.project.storage.domain.HwPayment;
import com.dhecp.project.storage.domain.HwPaymentson;
import com.dhecp.project.storage.domain.HwReconcileCkson;
import com.dhecp.project.storage.enums.TailprogramEnum;
import com.dhecp.project.storage.mapper.*;
import com.dhecp.project.storage.service.HwPaymentService;
import com.dhecp.project.system.service.SysDictionaryForFieldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * 海外付款单(HW_Payment)服务实现类
 *
 * @author fxz
 * @since 2023-09-14 23:27:29
 */
@Service
public class HwPaymentServiceImpl extends BaseModuleServiceImpl implements HwPaymentService {
    @Autowired
    private HwPaymentMapper hwPaymentMapper;
    
    @Autowired
    private SysDictionaryForFieldService dictionaryForFieldService;

    @Autowired
    private HwPaymentSonMapper hwPaymentSonMapper;

    @Autowired
    private HwReconcileMapper hwReconcileMapper;

    @Autowired
    private HwTailprogramMapper hwTailprogramMapper;

    @Autowired
    private HwReconcileCksonMapper hwReconcileCksonMapper;


    /**
     * 通过guid查询单条数据
     *
     * @param params 对象
     * @return 实例对象
     */
    @Override
    public HwPayment queryFirstRecord(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return hwPaymentMapper.selectFirstRecordByNid(params);
    }



    /**
    * 查询列表数据
    */
    @Override
    public List<HwPayment> queryList(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        return hwPaymentMapper.select(params);
    }

    /**
    * 查询明细列表数据
    */
    @Override
    public List<HwPayment> queryListSoList(Map<String, Object> params) throws Exception{
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_WHERE, dictionaryForFieldService.getWhereStr(params));	//常规查询条件SQL语句
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        if (params.get("field") == null || params.get("field") == ""){
            String orderBy = "t1.bid DESC";
            PageUtils.startPageOrder(orderBy);
        }else{
            PageUtils.startPage();
        }
        return hwPaymentMapper.querySoList(params);
    }

    @Override
    @Transactional
    public AjaxResult saveData(Map<String, Object> params) {
        params.put("businessEntity", new HwPayment());
        Map<String, Object> params3 = new HashMap<String, Object>();

//        params.put("isAuto", false);
        AjaxResult ajaxResult = this.saveDataBase(params);

        Map<String, Object> infoMap = (Map<String, Object>) ajaxResult.get("infoMap");
        String resNid = infoMap.get("nid").toString();

        HwPayment hwPayment = JSON.parseObject(params.get("infoMap").toString(), HwPayment.class);
        List<HwPaymentson> onSonData = new ArrayList<>();
        if (params.containsKey("sonData")){
            onSonData = JSON.parseArray(params.get("infoItems").toString(), HwPaymentson.class);
        }

        List<RecordCheck> guidMapList = hwPaymentMapper.findRecords(resNid);

        Map<String, Object> guidMap = new HashMap<String, Object>();
        if (!guidMapList.isEmpty()){
            if (infoMap.get("newNid") != null && "1".equals(infoMap.get("newNid").toString())){ //单号重复验证
                throw new RuntimeException(MessageUtils.message("module.error.retry"));
            }
            for (RecordCheck recordCheck : guidMapList){
                if (recordCheck != null && recordCheck.getGuid() != null){
                    guidMap.put(recordCheck.getGuid().toString(), "1");
                }
            }
        }
        if (onSonData == null || onSonData.size() == 0){
            resNid = "0";
        }else{
            resNid = infoMap.get("nid").toString();
            String guid = "";
            if (hwPayment.getGuid() == null){
                guid = RandomValueUtils.getGUID();
                hwPayment.setGuid(guid);
            }else{
                guid = hwPayment.getGuid().toString();
            }

            for (String field : infoMap.keySet()) { //遍历非网格字段，并赋值到实体中
                Object fieldValue = infoMap.get(field);
                ReflectUtils.setValue(hwPayment, field, fieldValue);
            }

            BigDecimal money = BigDecimal.ZERO;
            for (HwPaymentson item : onSonData
            ) {
                //付款金额
                money = money.add(item.getSjAmount());
            }

            if (guidMap.get(guid) == null){
                hwPayment.setCode(hwPayment.getBid());
                hwPayment.setFkTol(money.setScale(2, BigDecimal.ROUND_HALF_UP));
                hwPaymentMapper.insert(hwPayment);
            }else{
                hwPayment.setFkTol(money.setScale(2, BigDecimal.ROUND_HALF_UP));
                hwPaymentMapper.update(hwPayment);
                guidMap.remove(guid);
            }
            List<HwPaymentson> lodData = hwPaymentSonMapper.queryListCode(hwPayment.getBid());
            if (lodData.size()>0){
                for (HwPaymentson item : lodData
                ) {
                    hwPaymentSonMapper.delete(item);

                    hwReconcileMapper.updateState(item.getDzBid(), TailprogramEnum.StateName.HAVERECONCILED.value);

                    params3.put("pBid",item.getDzBid());
                    //查询出库对账信息
                    List<HwReconcileCkson> hwReconcileCksonList = hwReconcileCksonMapper.select(params3);
                    for (HwReconcileCkson hwReconcileCkson :hwReconcileCksonList){
                        hwTailprogramMapper.updateState(hwReconcileCkson.getWcBid(), TailprogramEnum.StateName.HAVERECONCILED.value);
                    }
                }
            }


            for (HwPaymentson item : onSonData
            ) {
                item.setGuid(RandomValueUtils.getGUID());
                item.setPBid(hwPayment.getBid());
                hwPaymentSonMapper.insert(item);
                hwReconcileMapper.updateState(item.getDzBid(), TailprogramEnum.StateName.DURINGPAYMENT.value);

                params3.put("pBid",item.getDzBid());
                //查询出库对账信息
                List<HwReconcileCkson> hwReconcileCksonList = hwReconcileCksonMapper.select(params3);
                for (HwReconcileCkson hwReconcileCkson :hwReconcileCksonList){
                    hwTailprogramMapper.updateState(hwReconcileCkson.getWcBid(), TailprogramEnum.StateName.DURINGPAYMENT.value);

                }
            }
        }


        if (!guidMap.isEmpty()){
            for (String guid : guidMap.keySet()){
                List<HwPaymentson> lodData = hwPaymentSonMapper.queryListCode(hwPayment.getBid());
                hwPaymentMapper.delete(guid);
                for (HwPaymentson hwPaymentSon : lodData){
                    hwPaymentSonMapper.delete(hwPaymentSon);

                    hwReconcileMapper.updateState(hwPaymentSon.getDzBid(), TailprogramEnum.StateName.HAVERECONCILED.value);

                    params3.put("pBid",hwPaymentSon.getDzBid());
                    //查询出库对账信息
                    List<HwReconcileCkson> hwReconcileCksonList = hwReconcileCksonMapper.select(params3);
                    for (HwReconcileCkson hwReconcileCkson :hwReconcileCksonList){
                        hwTailprogramMapper.updateState(hwReconcileCkson.getWcBid(), TailprogramEnum.StateName.HAVERECONCILED.value);

                    }
                }
            }
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"),resNid);
    }

    /**
     *@Description: 查询前一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 前一单NID， data.bid 前一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:08
     */
    @Override
    public AjaxResult queryLastNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == ""){
            params.put("nid", "0");
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = hwPaymentMapper.selectLastNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfirstnid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }


    /**
     *@Description: 查询后一单NID、BID
     *@Param: [params] nid 必要参数：当前 单据编码
     *@return: com.dhecp.common.core.domain.AjaxResult  (data.nid 后一单NID， data.bid 后一单BID)
     *@Author: hlf
     *@date: 2022-05-09 10:09
     */
    @Override
    public AjaxResult queryNextNid(Map<String, Object> params) throws Exception {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (params.get("nid") == null || params.get("nid") == "" || "0".equals(params.get("nid").toString())){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        params.put(DataFiltering.TABLE_ALIAS, "t1");	//查询表别名
        params.put(DataFiltering.DATA_SCODE, dictionaryForFieldService.getDataScode(params));	//数据权限查询条件SQL语句
        ModuleNID moduleNID = hwPaymentMapper.selectNextNid(params);
        if (moduleNID == null){
            dataMap.put("nid", "0");
            dataMap.put("bid", "0");
            return AjaxResult.warn(MessageUtils.message("module.warn.isfinallynid"), TypeUtils.mapToJson(dataMap).toString());
        }
        dataMap.put("nid", moduleNID.getNid().toString());
        dataMap.put("bid", moduleNID.getBid().toString());
        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), TypeUtils.mapToJson(dataMap).toString());
    }

    /**
     *@Description: 流转  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowGo(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<HwPayment> businessDataList = hwPaymentMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "go");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (HwPayment businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            hwPaymentMapper.updateFlow(updateFlow);

            if (updateFlow.getActiveFlow().equals("end")){
                List<HwPaymentson> hwPaymentsonList = hwPaymentSonMapper.queryListCode(businessData.getBid());
                for (HwPaymentson hwPaymentson : hwPaymentsonList){
                    hwReconcileMapper.updateState(hwPaymentson.getDzBid(), TailprogramEnum.StateName.ACCOUNTPAID.value);

                    Map<String, Object> params3 = new HashMap<String, Object>();
                    params3.put("pBid",hwPaymentson.getDzBid());
                    List<HwReconcileCkson> hwReconcileCksonList1 = hwReconcileCksonMapper.select(params3);
                    for (HwReconcileCkson hwReconcileCkson : hwReconcileCksonList1){
                        //已付款
                        hwTailprogramMapper.updateState(hwReconcileCkson.getWcBid(), TailprogramEnum.StateName.ACCOUNTPAID.value);
                    }
                }
            }
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }

    /**
     *@Description: 退回  —— 添加流程任务、修改流程状态及生效标志
     *@Param: [params] tableDataId 必要参数：单据编码（nid）
     *@return: com.dhecp.common.core.domain.AjaxResult
     *@Author: hlf
     *@date: 2022-05-09 10:11
     */
    @Override
    @Transactional(timeout=120,propagation= Propagation.REQUIRES_NEW)
    public AjaxResult updateFlowBack(Map<String, Object> params) {
        Map<String, Object> infoMap = new HashMap<String, Object>();
        String nid = "0";
        if (params.get("tableDataId") == null || params.get("tableDataId") ==""){
            return AjaxResult.error(MessageUtils.message("module.error.lack","单据编码【tableDataId】"));
        }else{
            nid = params.get("tableDataId").toString();
        }
        params.put("nid", nid);
        List<HwPayment> businessDataList = hwPaymentMapper.selectByNid(params);
        if (businessDataList == null || businessDataList.size() == 0){
            return AjaxResult.error(MessageUtils.message("module.error.nodata"));
        }else{
            infoMap.put("cid", businessDataList.get(0).getCid());
            infoMap.put("bUser", businessDataList.get(0).getbUser());
            infoMap.put("bDept", businessDataList.get(0).getbDept());
            infoMap.put("procInstId", businessDataList.get(0).getProcInstId());
            infoMap.put("activeFlow", businessDataList.get(0).getActiveFlow());
            infoMap.put("createTime", businessDataList.get(0).getCreateTime());
            params.put("infoMap", TypeUtils.mapToJson(infoMap).toString());
            params.put("activeFlowOld", businessDataList.get(0).getActiveFlow());
        }

        //流程处理公共方法，返回单据（流转、回退等）后的流程状态信息
        if (params.get("optType") == null || params.get("optType") == ""){
            params.put("optType", "back");
        }
        UpdateFlow updateFlow = new UpdateFlow();
        updateFlow = this.FlowDealBase(params);

        for (HwPayment businessData : businessDataList) {
            updateFlow.setGuid(businessData.getGuid().toString());
            hwPaymentMapper.updateFlow(updateFlow);

            if (infoMap.get("activeFlow").equals("end")){
                List<HwPaymentson> hwPaymentsonList = hwPaymentSonMapper.queryListCode(businessData.getBid());
                for (HwPaymentson hwPaymentson : hwPaymentsonList){
                    hwReconcileMapper.updateState(hwPaymentson.getDzBid(), TailprogramEnum.StateName.DURINGPAYMENT.value);

                    Map<String, Object> params3 = new HashMap<String, Object>();
                    params3.put("pBid",hwPaymentson.getDzBid());
                    List<HwReconcileCkson> hwReconcileCksonList1 = hwReconcileCksonMapper.select(params3);
                    for (HwReconcileCkson hwReconcileCkson : hwReconcileCksonList1){
                        //付款中
                        hwTailprogramMapper.updateState(hwReconcileCkson.getWcBid(), TailprogramEnum.StateName.DURINGPAYMENT.value);
                    }
                }
            }
        }

        return AjaxResult.success(MessageUtils.message("module.success.issuccess"), nid);
    }


}

